import React, { useEffect, useState } from 'react';
import styles from '../style/index.module.less';
import {
  Card,
  Message,
  Modal,
  Select,
  Skeleton,
  Typography,
} from '@arco-design/web-react';
import { Owner, Role, User } from '@/api/interface/authentication';
import { Descriptions } from '@arco-design/web-react';
import {
  OwnerList,
  UpdateOwner,
  UserListAll,
} from '@/api/modules/authentication';

const { Title, Text } = Typography;
const { Option } = Select;

interface Props {
  lang: string;
  t: unknown;
  owner: Role;
}

function OwnerPage({ lang, t, owner }: Props) {
  useEffect(() => {
    getOwnerList();
  }, []);

  const [userList, setUserList] = useState<{ [key: string]: User[] }>({});
  const [loading, setLoading] = useState(false);
  const [userIds, setUserIds] = useState({});

  const [ownerList, setOwnerList] = useState<Owner[]>([]);
  const getOwnerList = async () => {
    try {
      setLoading(true);
      const { data: ownerData } = await OwnerList();
      setOwnerList(ownerData);

      const newUserList = { ...userList };

      for (const item of ownerData) {
        const { data } = await UserListAll({ name: '', orgId: item.id });
        newUserList[item.name] = data;
      }
      setUserList(newUserList);

      setUserIds((prevUserIds) => {
        return ownerData.reduce((acc, item) => {
          if (item.superAdminId !== null) {
            const user = newUserList[item.name]?.find(
              (v) => v.id === item.superAdminId
            );
            if (user) return { ...acc, [item.id]: user.account };
          }
          return acc;
        }, prevUserIds);
      });
    } finally {
      setLoading(false);
    }
  };

  const OwnerItem = (item) => {
    const changeUser = (data) => {
      Modal.warning({
        title: t['auth.operations.permission'],
        closable: true,
        content: (
          <>
            {`${t['auth.owner.modal.title1']} ${data.label} (${
              t['auth.owner.modal.title2']
            }: ${data.value}) ${t['auth.owner.modal.title3']} [${
              (lang === 'en-US'
                ? item.emirate?.value.en
                : item.emirate?.value.ar) ?? '--'
            }]`}
            <br />
            <br />
            {t['auth.owner.modal.title4']}
          </>
        ),
        okButtonProps: { status: 'danger' },
        okText: `${t['auth.operations.confirm']}`,
        style: { textAlign: 'center', width: '700px' },
        onOk: async () => {
          const user = userList[item.name]?.find(
            (item) => item.account === data.value
          );
          await UpdateOwner({
            id: item.id,
            superAdminId: user.id,
            name: user.name,
            account: user.account,
            email: user.email,
            phone: user.phone,
          });
          setUserIds({ ...userIds, [item.id]: user.account });
          Message.success(t['auth.save.success']);
        },
      });
    };

    return [
      {
        label: t['auth.owner.institution'],
        value:
          (lang === 'en-US'
            ? item.emirate?.value.en
            : item.emirate?.value.ar) ?? '--',
      },
      {
        label: t['auth.owner.organization'],
        value: item.description ?? '--',
      },
      {
        label: t['auth.owner.abbreviation'],
        value: item.name ?? '--',
      },
      {
        label: t['auth.owner.superAdmin'],
        value: (
          <Select
            placeholder="Please select"
            showSearch
            style={{ width: '250px' }}
            labelInValue={true}
            value={userIds ? userIds[item.id] : undefined}
            filterOption={(inputValue, option) =>
              option.props.children
                .toLowerCase()
                .indexOf(inputValue.toLowerCase()) >= 0
            }
            onChange={(value) => changeUser(value)}
          >
            {userList[item.name]?.map((user) => (
              <Option key={user?.account} value={user?.account}>
                {user?.name}
              </Option>
            ))}
          </Select>
        ),
      },
    ];
  };

  return (
    <>
      <Card style={{ marginBottom: '15px' }}>
        <div className={styles['owner-title']}>
          <Title heading={5}>
            {owner[lang === 'ar-EG' ? 'nameAr' : 'name'] || owner['name']}
          </Title>
          <Text className="ltr">
            {' '}
            {owner[lang === 'ar-EG' ? 'descriptionAr' : 'description'] ||
              owner['description']}
          </Text>
        </div>
      </Card>
      <Card>
        <Skeleton text={{ rows: 5, width: ['100%'] }} loading={loading}>
          <Title heading={5}>{t['auth.owner.title']}</Title>
          {ownerList.map((item) => {
            return (
              <Descriptions
                border
                colon="："
                key={item.id}
                layout="inline-horizontal"
                data={OwnerItem(item)}
                column={4}
                style={{ marginBottom: '15px' }}
              />
            );
          })}
        </Skeleton>
      </Card>
    </>
  );
}

export default OwnerPage;
